package com.parktech.sun.web.controller.management.industryinfo;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.industryinfo.IndustryInfo;
import com.parktech.sun.domain.model.industryinfo.IndustryInfoAttachment;
import com.parktech.sun.domain.model.industryinfo.IndustryInfoCategory;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.industryinfo.IndustryInfoService;
import com.parktech.sun.utils.FileHelper;
import com.parktech.sun.utils.ImageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: Think
 * Date: 11-1-13
 * Time: 下午9:08
 */
@Controller
@RequestMapping("/management/industryinfos")
public class IndustryInfoController {

    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private IndustryInfoService industryInfoService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public IndustryInfoController(IndustryInfoService industryInfoService) {
        this.industryInfoService = industryInfoService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute IndustryInfoSearchForm industryInfoSearchForm) {

        Page page = new Page(pageSize, industryInfoSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/industryinfo/industryInfoSearch");

        return modelAndView.addObject(
                industryInfoService.search(
                        industryInfoSearchForm.getTitle(), industryInfoSearchForm.getCategory(), industryInfoSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("industryInfoIds") Long[] industryInfoIds) {
        industryInfoService.deleteAll(industryInfoIds);
        return "redirect:search";
    }

    @ModelAttribute("allCategories")
    public List<IndustryInfoCategory> populateAllCategories() {
        return industryInfoService.searchCategory(null, new Page(1000, 1)).getResult();
    }

    @ModelAttribute("industryInfo")
    public IndustryInfo populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new IndustryInfo();
        }
        return industryInfoService.getById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{industryInfoId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long industryInfoId, Model model) {
        IndustryInfo industryInfo = industryInfoService.getById(industryInfoId);
        model.addAttribute(industryInfo);
        return "management/industryinfo/industryInfoForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new IndustryInfo());
        return "management/industryinfo/industryInfoForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid IndustryInfo industryInfo, BindingResult result,
                       @RequestParam("attachments") MultipartFile[] attachments,
                       @RequestParam("image") MultipartFile image,
                       @RequestParam("delAttachmentIds") Long[] delAttachmentIds, HttpServletRequest request)
            throws IOException {

        if (result.hasErrors()) {
            return "management/industryinfo/industryInfoForm";
        }
        industryInfoService.clearThenSaveOrUpdateBean(industryInfo);

        if (delAttachmentIds != null) {
            deleteAttachments(industryInfo, delAttachmentIds, request.getSession().getServletContext());
        }

        if (image != null && !image.isEmpty()) {
            processImage(industryInfo, image, request.getSession().getServletContext());
        }

        if (attachments.length > 0) {
            processAttachments(industryInfo, attachments, request.getSession().getServletContext());
        }
        industryInfoService.saveOrUpdateBean(industryInfo);

        return "redirect:/management/industryinfos/search";
    }

    private void processImage(IndustryInfo industryInfo, MultipartFile image, ServletContext servletContext) throws IOException {

        String industryInfoPath = servletContext.getRealPath("/upload/industryInfo/" + industryInfo.getId());
        File industryInfoDir = new File(industryInfoPath);
        if (!industryInfoDir.exists()) industryInfoDir.mkdirs();

        File imageFile = new File(industryInfoDir, image.getOriginalFilename());
        if (imageFile.exists()) {
            imageFile.delete();
        }
        FileHelper.saveFile(image.getInputStream(), imageFile);
        industryInfo.setImageName(image.getOriginalFilename());
    }

    private void deleteAttachments(IndustryInfo industryInfo, Long[] delAttachmentIds, ServletContext servletContext) {
        List<IndustryInfoAttachment> attachmentList = industryInfo.getAttachmentList();
        if (attachmentList == null) {
            return;
        }
        String industryInfoPath = servletContext.getRealPath("/upload/industryInfo/" + industryInfo.getId());
        File industryInfoDir = new File(industryInfoPath);
        if (!industryInfoDir.exists()) industryInfoDir.mkdirs();

        for (Iterator<IndustryInfoAttachment> iterator = attachmentList.iterator(); iterator.hasNext();) {
            IndustryInfoAttachment attachment = iterator.next();
            for (Long delAttachmentId : delAttachmentIds) {
                if (attachment.getId().equals(delAttachmentId)) {
                    iterator.remove();
                    attachmentList.remove(attachment);
                    attachment.setIndustryInfo(null);
                    File toDelFile = new File(industryInfoDir, attachment.getName());
                    if (toDelFile.exists()) toDelFile.delete();
                }
            }
        }
    }

    private void processAttachments(IndustryInfo industryInfo, MultipartFile[] attachments, ServletContext servletContext) throws IOException {

        String industryInfoPath = servletContext.getRealPath("/upload/industryInfo/" + industryInfo.getId());
        File industryInfoDir = new File(industryInfoPath);
        if (!industryInfoDir.exists()) industryInfoDir.mkdirs();

        List<IndustryInfoAttachment> attachmentList = industryInfo.getAttachmentList();
        if (attachmentList == null) {
            attachmentList = new ArrayList<IndustryInfoAttachment>();
            industryInfo.setAttachmentList(attachmentList);
        }
        for (MultipartFile attachment : attachments) {
            if (attachment == null || attachment.isEmpty()) {
                continue;
            }
            String originalFilename = attachment.getOriginalFilename();
            File target = new File(industryInfoDir, attachment.getOriginalFilename());
            if (target.exists()) {
                target.delete();
            } else {
                attachmentList.add(new IndustryInfoAttachment(originalFilename, industryInfo));
            }

            FileHelper.saveFile(attachment.getInputStream(), target);
        }
    }


}
